package com.example.leetcode;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class LeetCode22 {
    public class ListNode {
        int val;
        LeetCode22.ListNode next;

        ListNode(int x) {
            val = x;
        }
        // 添加新的结点
        public void add(int newval) {
            LeetCode22.ListNode newNode = new LeetCode22.ListNode(newval);
            if(this.next == null)
                this.next = newNode;
            else
                this.next.add(newval);
        }
        // 打印链表
        public void print() {
            System.out.print(this.val);
            if(this.next != null)
            {
                System.out.print("-->");
                this.next.print();
            }
        }
    }
    @Test
    void contextLoads() {
        LeetCode22.ListNode head=new LeetCode22.ListNode(1);
        head.add(2);
        head.add(3);
        head.add(4);
        head.add(5);
        head.print();
        getKthFromEnd(head,2);

        System.out.println("hello world");
    }
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode res=head;
        int total=0;
        while(head!=null){
            head=head.next;
            total++;
        }
        int j=total-k;
        while(res!=null){
            if(j==0){
                return res;
            }
            res=res.next;
            j--;

        }
        return res;
    }
}
